import os
import time
import json
import subprocess

import platform
p = platform.system()
config = []

# 获取定时任务配置
def getConfig():
  defaultPath = os.path.abspath('config.default.json')
  userPath = os.path.abspath('config.user.json')
  config = []
  if os.path.exists(userPath):
    with open(userPath, encoding='utf-8') as a:
      result = json.load(a)
      config = config + result
  elif os.path.exists(defaultPath):
    with open(defaultPath, encoding='utf-8') as a:
      result = json.load(a)
      config = config + result
  return config

# 日志系统
def log(text):
  timestamp = time.localtime(time.time())
  fileName = time.strftime('%Y-%m-%d', timestamp) + '.log'
  path = os.path.abspath('logs' + '/' + fileName)
  print(text)
  with open(path, 'a', encoding='utf-8')as file:
    file.write(text + '\n')

# 获取运行命令
def getCmd(config):
  global p
  cmd = ''
  if p == 'Windows':
    cmd = config['win_cmd']
  elif p == 'Linux':
    cmd = config['linux_cmd']
  else:
    cmd = config['mac_cmd']
  return cmd

# 获取当前时间
def getCurrentTime():
  timestamp = time.localtime(time.time())
  now = time.strftime('%Y-%m-%d %H:%M:%S', timestamp)
  return now

# 运行命令
def command(cmd, name):
  now = getCurrentTime()
  log("[ " + now + " ] " + "触发的定时任务名称：" + name)
  log("[ " + now + " ] " + "运行命令：" + cmd)
  process = subprocess.Popen(cmd, shell=True)

def loop():
  global config
  while True:
    time.sleep(1)
    timestamp = time.localtime(time.time())
    for i in range(len(config)):
      item = config[i]
      enable = True
      immediately = False
      if 'enable' in item.keys(): enable = item['enable']
      if 'immediately' in item.keys(): immediately = item['immediately']
      if enable == False: continue
      name = item['name']
      timePoint = item['time_point']
      format = item['format']
      cmd = getCmd(item)
      targetTime = time.strftime(format, timestamp)
      if immediately == True:
        command(cmd = cmd, name = name)
        item['immediately'] = False
      if targetTime in timePoint:
        command(cmd = cmd, name = name)

if __name__ == "__main__":
  log("[ " + getCurrentTime() + " ] " + "您的平台是：" + p)
  config = getConfig()
  loop()
